package sk.uniba.fmph.asdf.gui.views;

import com.alee.laf.label.WebLabel;
import com.alee.laf.optionpane.WebOptionPane;
import com.alee.laf.text.WebPasswordField;
import com.alee.laf.text.WebTextField;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import net.miginfocom.swing.MigLayout;
import sk.uniba.fmph.asdf.db.Account;
import sk.uniba.fmph.asdf.db.AccountManager;
import sk.uniba.fmph.asdf.db.FullName;
import sk.uniba.fmph.asdf.exceptions.DatabaseException;
import sk.uniba.fmph.asdf.exceptions.OfflineException;
import sk.uniba.fmph.asdf.gui.GuiUtils;

/**
 * Prihlasovací dialog. Zobrazuje formulár na zadanie prihlasovacích údajov a
 * sprostredkuje prihlásenie.
 *
 * @author Jakub Gaľ
 */
public class RegistrationView extends View {

	private View parent;
	private WebTextField firstNameField;
	private WebTextField surnameField;
	private WebTextField usernameField;
	private WebPasswordField passwordField;
	private WebPasswordField confirmPasswordField;
	private JButton cancelBtn;
	private JButton registerBtn;

	public RegistrationView(View parent) {
		super(JFrame.DISPOSE_ON_CLOSE);
		this.parent = parent;
		initComponents();
	}

	/**
	 * Inicializacia komponentov
	 */
	@Override
	protected final void initComponents() {
		setTitle("Registrácia");

		getContentPane().setLayout(new MigLayout("", "", "[][][][][][][][]24[]"));

		WebLabel firstNameLabel = GuiUtils.getShadedLabel("Krstné meno");
		WebLabel surnameLabel = GuiUtils.getShadedLabel("Priezvisko");
		WebLabel usernameLabel = GuiUtils.getShadedLabel("E-mail (prihlasovacie meno)");
		WebLabel passwordLabel = GuiUtils.getShadedLabel("Heslo");
		WebLabel confirmPasswordLabel = GuiUtils.getShadedLabel("Potvrdťe heslo");

		firstNameField = new WebTextField(12);
		surnameField = new WebTextField(12);
		usernameField = new WebTextField();
		passwordField = new WebPasswordField();
		confirmPasswordField = new WebPasswordField();

		cancelBtn = new JButton("Zrušiť", GuiUtils.getIcon("cancel"));
		cancelBtn.addActionListener(this);
		registerBtn = new JButton("Vytvoriť účet", GuiUtils.getIcon("sign_up"));
		registerBtn.addActionListener(this);
		getRootPane().setDefaultButton(registerBtn);

		add(firstNameLabel);
		add(surnameLabel, "wrap");
		add(firstNameField, "growx");
		add(surnameField, "growx, wrap");
		add(usernameLabel, "span 2, wrap");
		add(usernameField, "span 2, growx, wrap");
		add(passwordLabel, "span 2, wrap");
		add(passwordField, "span 2, growx, wrap");
		add(confirmPasswordLabel, "span 2, wrap");
		add(confirmPasswordField, "span 2, growx, wrap");
		add(cancelBtn, "align left");
		add(registerBtn, "align right");
	}

	/**
	 * Spracovanie kliknutia na tlacitka
	 *
	 * @param evt
	 */
	@Override
	public void actionPerformed(java.awt.event.ActionEvent evt) {
		if (evt.getSource() == cancelBtn) {
			confirmCancel();
		} else if (evt.getSource() == registerBtn) {
			register();
		}
	}

    /**
     * Zobrazenie okna pre potvrdenie zrusenia procesu registracie
     */
	private void confirmCancel() {
		Object[] options = {"Nie", "Áno"};
		int option = WebOptionPane.showOptionDialog(rootPane, "Prajete si zrušiť proces registrácie?", "Potvrdenie", WebOptionPane.YES_NO_OPTION, WebOptionPane.QUESTION_MESSAGE, null, options, options[0]);
		if (option == 1) {
			closeWindow();
		}
	}

	/**
	 * Spracovanie kliknutia na tlacidlo Vytvorit ucet. Overi korektnost zadanych
	 * udajov a pokusi sa pouzivatela registrovat. V pripade vynimky zobrazi
	 * chybovy dialog inak pouzivatela automaticky prihlasi a oznami uspesnu
	 * registraciu.
	 *
	 */
	private void register() {
		String firstName = firstNameField.getText();
		String surname = surnameField.getText();
		String username = usernameField.getText();
		String password = new String(passwordField.getPassword());
		String confirmedPassword = new String(confirmPasswordField.getPassword());

		if (firstName.isEmpty() || surname.isEmpty() || username.isEmpty() || password.isEmpty() || confirmedPassword.isEmpty()) {
			JOptionPane.showMessageDialog(rootPane, "Je potrebné vypniť všetky údaje.", "Chyba!", JOptionPane.ERROR_MESSAGE);
		} else if (!Account.validEmail.matcher(username).matches()) {
			JOptionPane.showMessageDialog(rootPane, "Nesprávny formát e-mailu.", "Chyba!", JOptionPane.ERROR_MESSAGE);
		} else if (!password.equals(confirmedPassword)) {
			JOptionPane.showMessageDialog(rootPane, "Heslá sa nezhodujú!", "Chyba!", JOptionPane.ERROR_MESSAGE);
		} else {
			try {
				AccountManager.createNewUser(username, new FullName(firstName, surname), password);
				JOptionPane.showMessageDialog(rootPane, "Registrácia prebehla úspešne!", "Oznam", JOptionPane.INFORMATION_MESSAGE);
				closeWindow();
			} catch (DatabaseException e) {
				System.err.println(e.getMessage());
				JOptionPane.showMessageDialog(rootPane, "Registrácia zlyhala pre chybu v databáze! \n" + e.getMessage(), "Chyba!", JOptionPane.ERROR_MESSAGE);
			} catch (OfflineException e) {
				JOptionPane.showMessageDialog(rootPane, "Nepodarilo sa pripojiť k databáze.", "Chyba!", JOptionPane.ERROR_MESSAGE);
			}
		}
	}

	@Override
	public void closeWindow() {
		parent.setEnabled(true);
		super.closeWindow();
	}
}